import 'package:fish_redux/fish_redux.dart';
import '../../../app_files.dart';
import 'dart:io';
import 'action.dart';
import 'state.dart';

Effect<PatrolReasonViewState> buildEffect() {
  return combineEffects(<Object, Effect<PatrolReasonViewState>>{
    PatrolReasonViewAction.onTapAddPic: _onTapAddPic,
    PatrolReasonViewAction.onTapPic: _onTapPic,
    PatrolReasonViewAction.onSubmit: _onSubmit,
  });
}

void _onTapAddPic(Action action, Context<PatrolReasonViewState> ctx) async {
  File imgFile = await CommonUtils.showImagePicker(ctx.context);
  if (imgFile != null) {
    ctx.state.orderPhoto.add(imgFile);
    ctx.dispatch(PatrolReasonViewActionCreator.onAction());
  }
}

void _onTapPic(Action action, Context<PatrolReasonViewState> ctx) async {
  pushPhoto(file) async {
    List<GalleryExampleItem> items = ctx.state.orderPhoto.map((e) {
      int index = ctx.state.orderPhoto.indexOf(e);
      return GalleryExampleItem(
        id: '$index',
        resource: e,
      );
    }).toList();
    items = await CommonUtils.showPhotoAlbumView(
      ctx.context,
      initialIndex: ctx.state.orderPhoto.indexOf(file),
      galleryItems: items,
    );
  }

  var file = action.payload;
  int res =
      await CommonUtils.showActionSheet(ctx.context, button: ['查看', '删除']);
  if (res == 1) {
    ctx.state.orderPhoto.remove(file);
    ctx.dispatch(PatrolReasonViewActionCreator.onAction());
  } else if (res == 0) {
    pushPhoto(file);
  }
}

void _onSubmit(Action action, Context<PatrolReasonViewState> ctx) async {
  if (ctx.state.textEditingController.text.length == 0) {
    CommonUtils.showErrorInfo(ctx.context, '请填写问题描述');
    return;
  }
  String img = '';
  if (ctx.state.orderPhoto.length != 0) {
    CommonUtils.showWaitLoading(ctx.context, descText: '上传图片中');
    List<String> images =
        await CommonNetWork.multiUploadImgs(ctx.state.orderPhoto);
    Navigator.pop(ctx.context);
    img = images.join(',');
  }
  String reason = ctx.state.textEditingController.text;
  CommonUtils.showWaitLoading(ctx.context);
  ResultData res = await CommonNetWork.staffPatrolStatus(
    workStatus: 4,
    reasonContent: reason,
    reasonImage: img,
    orderID: ctx.state.info.orderID,
  );
  Navigator.pop(ctx.context);
  if (res.success) {
    bus.emit('refreshList');
    await CommonUtils.showAlertView(ctx.context, '提交成功');
    Navigator.pop(ctx.context);
  } else {
    CommonUtils.showErrorInfo(ctx.context, res.desc);
  }
}
